import { Toast } from 'vant';
import QRCode from 'qrcodejs2';
var commJs = {
  objKeys(value) {
    const keys = []
    for (const ke in value) {
      keys.push(ke)
    }
    return keys
  },

  objValues(value) {
    const values = []
    for (const va in value) {
      values.push(value[va])
    }
    return values
  },
  getDayFormatDate(seperator1, day) { //获取当前日期;
    day.setTime(day.getTime());
    var year = day.getFullYear();
    var month = day.getMonth() + 1;
    var strDate = day.getDate();

    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },
  getDayFormatDate3(day) { //获取当前日期;
    day.setTime(day.getTime());
    var year = day.getFullYear();
    var month = day.getMonth() + 1;
    var strDate = day.getDate();

    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = year + '年' + month + '月' + strDate + '日';
    return currentdate;
  },
  getDayFormatDate2(seperator1, day) { //获取当前日期;
    day.setTime(day.getTime());
    var month = day.getMonth() + 1;
    var strDate = day.getDate();

    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    var currentdate = month + seperator1 + strDate;
    return currentdate;
  },
  lowerJSONKey(jsonObj) { //json的key改成小写
    for (var key in jsonObj) {
      if (key != 'reportId') {
        jsonObj[key.toLowerCase()] = jsonObj[key];

        if (typeof jsonObj[key] == 'object' && jsonObj[key] != null) {
          jsonObj[key].forEach((item, index) => {
            for (let kind in item) {
              jsonObj[key][index][kind.toLowerCase()] = item[kind];
              delete (item[kind]);
            }
          });
        } else {
          delete (jsonObj[key]);
        }
      }
    }
    return jsonObj;
  },
  toMoney(num) { // 将数字转换成金额显示
    let sign = '';
    if (!isNaN(num)) {
      if (num.toString().substring(1, 0) == '-') {
        num = num.toString().substr(1);
        sign = '-';
      }

      num = typeof num == 'number' ? num : parseFloat(num); // 判断是否是字符串如果是字符串转成数字
      num = num.toFixed(2); // 保留两位
      // num = num.toLocaleString(); // 转成金额显示模式
      let numLeft = num.slice(0, num.lastIndexOf('.')),
        numRight = num.slice(num.lastIndexOf('.'));
      var result = '',
        counter = 0;
      numLeft = (numLeft || 0).toString();
      for (var i = numLeft.length - 1; i >= 0; i--) {
        counter++;
        result = numLeft.charAt(i) + result;
        if (!(counter % 3) && i != 0) {
          result = ',' + result;
        }
      }
      return sign + result + numRight;
    } else {
      return num = null;
    }
  },
  //点击复制
  copyPath(eleId) {
    const range = document.createRange();
    range.selectNode(document.getElementById(eleId));

    const selection = window.getSelection();
    if (selection.rangeCount > 0) {
      selection.removeAllRanges();
    }
    selection.addRange(range);
    document.execCommand('Copy');
    Toast({
      message: '复制成功',
      type: 'success'
    });
  },
  // 生成二维码图片
  getCodeImg(name, wid, hei, url) {
    let qrcode = new QRCode(name, {
      width: wid,
      height: hei,
      render: 'canvas', //设置渲染方式 table canvas
      typeNumber: -1, //计算模式
      correctLevel: 0, //纠错等级
      background: '#ffffff', //背景颜色
      foreground: '#000000', //前景颜色
      text: url //链接
    });
  },
  // 只赋值formData原有的key
  margeObj(obj1, obj2) {
    Object.keys(obj2).forEach(key => {
      obj2[key] = obj1[key];
    });
    return obj2;
  },
  // 判断设备
  testPlat() {
    var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
      //android终端
      return 0;
    } else if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      //ios终端
      return 1;
    } else {
      return 2;
    }
  },
  // 判断字符长度
  gblen(str) {
    var totalByteLength = 0;
    var i;
    var charCode;
    for (i = 0; i < str.length; i++) {
      charCode = str.charCodeAt(i);
      if (charCode < 0x007f) { //0x0000 - 0x007F:1字节
        totalByteLength += 1;
      } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) { //0x0080 - 0x07FF:2字节
        totalByteLength += 2;
      } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) { //0x0800 - 0xFFFF:3字节
        totalByteLength += 3;
      } else if ((0x010000 <= charCode) && (charCode <= 0x10FFFF)) { //此分支基本用不上//0x010000 - 0x10FFFF:4字节
        totalByteLength += 4;
      }
    }
    return totalByteLength;
  },
  // 严格的身份证号验证
  isCardID(sId, show=true) {
    if (!(/(^\d{15}$)|(^\d{17}(\d|X|x)$)/).test(sId)) {
      if (show) {
        Toast('你输入的身份证长度或格式错误');
      }
      return false;
    }
    //身份证城市
    var aCity = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外' };
    if (!aCity[parseInt(sId.substr(0, 2))]) {
      if (show) {
        Toast('你的身份证地区非法');
      }
      return false;
    }

    // 出生日期验证
    var sBirthday = (sId.substr(6, 4) + '-' + Number(sId.substr(10, 2)) + '-' + Number(sId.substr(12, 2))).replace(/-/g, '/'),
      d = new Date(sBirthday);
    if (sBirthday != (d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate())) {
      if (show) {
        Toast('身份证上的出生日期非法');
      }
      return false;
    }

    // 身份证号码校验
    var sum = 0,
      weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
      codes = '10X98765432';
    for (var i = 0; i < sId.length - 1; i++) {
      sum += sId[i] * weights[i];
    }
    var last = codes[sum % 11]; //计算出来的最后一位身份证号码
    if (sId[sId.length - 1] != last) {
      if (show) {
        Toast('你输入的身份证号非法');
      }
      return false;
    }

    return true;
  },
  // 交换数组两个元素位置
  swapArr(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  },
  // 获取一年的自然周
  naturalWeek( year ) {
    var weeks = {};
    var eachWeek = [];
    var index = 1;
    var yearStart = new Date( year.toString() + '/1/1' ).valueOf();
    var yearEnd = new Date( (Number(year) + 1).toString() + '/1/1' ).valueOf() - 1;
    for ( var i = yearStart; i < yearEnd; i += 86400000 ) {
      var date = new Date(i).toLocaleDateString();
      var day = new Date(i).getDay();
      eachWeek.push( date );
      weeks[index] = eachWeek;
      if ( day === 0 ) {
        index += 1;
        eachWeek = [];
      }
    }
    return weeks;
  },
  // 计算数组的最大值
  calMax(arr) {
    let max = 0;
    arr.forEach((el) => {
      if (!(el === undefined || el === '')) {
        if (max < el) {
          max = el;
        }
      }
    });
    let maxint = Math.ceil(max / 9.5);//不让最高的值超过最上面的刻度
    let maxval = maxint * 10;//让显示的刻度是整数
    return maxval;
  },
  // 计算数组的最小值
  calMin(arr) {
    let min = 0;
    arr.forEach((el) => {
      if (!(el === undefined || el === '')) {
        if (min > el) {
          min = el;
        }
      }
    });
    let minint = Math.floor(min / 10);
    let minval = minint * 10;//让显示的刻度是整数
    return minval;
  },
  // 设置echarts百分号单位
  setUnit(params, all) {
    let html=params[0].name+"<br>";
    for(let i=0;i<params.length;i++){
      html+='<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:'+params[i].color+';"></span>'
      if((params[i].seriesName.indexOf('同比') != -1 ||
        params[i].seriesName.indexOf('进度') != -1 ||
        params[i].seriesName.indexOf('率') != -1 ||
        params[i].seriesName.indexOf('占比') != -1 ||
        params[i].seriesName.indexOf('GPS目标') != -1 ||
        params[i].seriesName.indexOf('GPS执行') != -1 ||
        params[i].seriesName.indexOf('执行GPS') != -1 ||
        params[i].seriesName.indexOf('目标GPS') != -1
      ) || all){
        html+=params[i].seriesName+":"+"&"+"n"+"b"+"s"+"p"+";"+`<span style="font-weight:bold;float:right;">${params[i].value}%</span>`+"<br>";
      }else{
        html+=params[i].seriesName+":"+"&"+"n"+"b"+"s"+"p"+";"+`<span style="font-weight:bold;float:right;">${params[i].value}</span>`+"<br>";
      }
    }
    return html;
  },
  // 处理堆叠label重叠问题
  labelFormatter(params) {
    const a = params.value
    if (a > 0) {
      return a
    } else {
      return ''
    }
  },
  // ios系统无法识别'-'的时间格式，会显示为NAN，处理方式先转为'/'，再用date.replace(/-/g, '/')替换
  formartDate(date) {
    return date.replace(/-/g, '/')
  },
  // 日期月份小于9补0 202208
  dateCompleZero(date) {
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    if (m <= 9) {
      return `${y}0${m}`
    } else {
      return `${y}${m}`
    }
  },
  // 计算dataZoom终止位置
  computedZoomEndIndex(list) {
    if (list.length > 10) {
      return 9;
    } else {
      return list.length - 1;
    }
  },
  // 设置echart柱状图顶部数字
  barItemStyle(color) {
    return {
      normal: {
        label: {
          show: true,
          position: 'top',
          fontSize: 10,
          color: color
        }
      }
    }
  }
};

export default commJs;
